package com.mahiru.mahiruaiagent.tools;

import cn.hutool.core.io.FileUtil;
import com.itextpdf.io.font.PdfEncodings;
import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Image;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.properties.TextAlignment;
import com.mahiru.mahiruaiagent.constant.FileConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.ResourceUtils;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.List;

/**
 * @author Enkidu
 */
public class PDFGenerationTool {

    private static final Logger logger = LoggerFactory.getLogger(PDFGenerationTool.class);
    private static final String FONT_PATH = "static/fonts/simsun.ttc";

    @Tool(description = "Generate a PDF file with given text content")
    public String generatePDF(
            @ToolParam(description = "Name of the file to save the generated PDF") String fileName,
            @ToolParam(description = "Content to be included in the PDF") String content) {
        return generatePDFWithImages(fileName, content, null);
    }

    @Tool(description = "Generate a PDF file with given content and images")
    public String generatePDFWithImages(
            @ToolParam(description = "Name of the file to save the generated PDF") String fileName,
            @ToolParam(description = "Text content to be included in the PDF") String content,
            @ToolParam(description = "List of image paths to be included in the PDF") List<String> imagePaths) {
        String fileDir = FileConstant.FILE_SAVE_DIR + "/pdf";
        String filePath = fileDir + "/" + fileName;
        if (!fileName.toLowerCase().endsWith(".pdf")) {
            filePath += ".pdf";
        }

        try {
            // 创建目录
            FileUtil.mkdir(fileDir);
            // 创建 PdfWriter 和 PdfDocument 对象
            try (PdfWriter writer = new PdfWriter(filePath);
                    PdfDocument pdf = new PdfDocument(writer);
                    Document document = new Document(pdf, PageSize.A4)) {

                // 配置字体 - 使用多种方式尝试加载中文字体
                PdfFont font = null;

                // 方法1: 尝试使用标准内置字体
                try {
                    font = PdfFontFactory.createFont("STSong-Light", "UniGB-UCS2-H");
                    logger.info("使用STSong-Light字体成功");
                } catch (Exception e1) {
                    logger.warn("无法加载STSong-Light字体: {}", e1.getMessage());

                    // 方法2: 尝试从classpath加载字体
                    try {
                        File fontFile = ResourceUtils.getFile("classpath:" + FONT_PATH);
                        if (fontFile.exists()) {
                            font = PdfFontFactory.createFont(fontFile.getAbsolutePath(), PdfEncodings.IDENTITY_H);
                            logger.info("从classpath加载字体成功: {}", fontFile.getAbsolutePath());
                        }
                    } catch (Exception e2) {
                        logger.warn("无法从classpath加载字体: {}", e2.getMessage());

                        // 方法3: 尝试从系统字体目录加载
                        try {
                            String systemFontPath = System.getenv("WINDIR") + "/Fonts/simfang.ttf";
                            File systemFont = new File(systemFontPath);
                            if (systemFont.exists()) {
                                font = PdfFontFactory.createFont(systemFontPath, PdfEncodings.IDENTITY_H);
                                logger.info("从系统加载字体成功: {}", systemFontPath);
                            }
                        } catch (Exception e3) {
                            logger.warn("无法从系统加载字体: {}", e3.getMessage());

                            // 最后尝试使用默认字体
                            try {
                                font = PdfFontFactory.createFont();
                                logger.info("使用默认字体");
                            } catch (Exception e4) {
                                logger.error("无法加载任何字体: {}", e4.getMessage());
                            }
                        }
                    }
                }

                if (font != null) {
                    document.setFont(font);
                }

                // 添加文本内容
                if (content != null && !content.isEmpty()) {
                    Paragraph paragraph = new Paragraph(content);
                    paragraph.setTextAlignment(TextAlignment.JUSTIFIED);
                    document.add(paragraph);
                }

                // 添加图片
                if (imagePaths != null && !imagePaths.isEmpty()) {
                    for (String imagePath : imagePaths) {
                        try {
                            Image img = new Image(ImageDataFactory.create(imagePath));
                            // 调整图片宽度适应页面
                            float pageWidth = document.getPdfDocument().getDefaultPageSize().getWidth() - 50;
                            float imageWidth = img.getImageWidth();

                            if (imageWidth > pageWidth) {
                                float ratio = pageWidth / imageWidth;
                                img.scale(ratio, ratio);
                            }

                            document.add(img);
                        } catch (Exception e) {
                            document.add(new Paragraph("无法加载图片: " + imagePath + ", 错误: " + e.getMessage()));
                        }
                    }
                }
            }
            return "PDF生成成功，保存路径: " + filePath;
        } catch (Exception e) {
            logger.error("生成PDF时出错", e);
            return "生成PDF时出错: " + e.getMessage();
        }
    }
}
